<template>
  <div>
    <el-dialog
      :title="formData.id?'编辑房产':'添加房产'"
      :visible="showDialog"
      @close="btnCancel"
    >
      <el-form ref="formData" :model="formData">
        <el-form-item label="经纪" prop="agent">
          <el-select v-model="agentValue" placeholder="全部经纪">
            <el-option v-for="item in agentOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="categoryValue" placeholder="全部分类">
            <el-option v-for="item in categoryOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item required label="标题" prop="title">
          <el-input v-model="formData.title" style="width:90%" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <!-- 判断是否有数据才显示 -->
          <el-tag
            v-for="tag in formData.tags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <!-- 输入添加 -->
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>

        </el-form-item>
        <el-form-item label="地址" prop="tags">
          <el-cascader
            v-model="selectedOptions"
            style="width:150px"
            size="large"
            :options="options"
            @change="handleChange"
          />
          <el-input v-model="formData.address" style="width:525px" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="formData.price" style="width:90%" />
        </el-form-item>
        <el-form-item required label="描述" prop="desc">
          <el-input v-model="formData.desc" type="textarea" :autosize="{ minRows: 3}" style="width:90%" />

        </el-form-item>
        <el-form-item label="内容" prop="content">
          <wangEnduit
            v-model="formData.content"
            style="marginLeft:40px;width:680px"
            :is-clear="isClear"
            :value="formData.content"
            @change="change"
          />
        </el-form-item>
        <el-form-item label="介绍图片" prop=" photos">
          <el-upload
            action="https://jsonplaceholder.typicode.com/posts/"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="image" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="封面" prop="image">
          <imageUpload ref="imageUpload" />
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button type="primary" size="small" @click="btnOk">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 引入地域选择器
import { regionDataPlus, CodeToText } from 'element-china-area-data'
import { getPropertyById, addproperty, delproperty } from '@/api/properties'
import wangEnduit from './wangEnduit.vue'
import { getCategories } from '@/api/categories'
import { jingji } from '@/api/jingji'
import imageUpload from '@/components/ImageUpLoad'

export default {
  components: {
    wangEnduit, imageUpload
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 经纪数据
      agentOption: [],
      agentValue: '',
      // 分类数据
      categoryOption: [],
      categoryValue: '',
      isClear: false,
      // 图片
      image: '',
      dialogVisible: false,
      // 地域
      options: regionDataPlus,
      selectedOptions: [],

      // 标签

      inputVisible: false,
      inputValue: '',
      // 表单
      formData: {
        agent: '',
        category: '',
        title: '',
        tags: [],
        address: '',
        price: '',
        desc: '',
        content: '',
        image: '',
        photos: []
      }
    }
  },
  watch: {
    formData(newObj) {
      console.log(54, newObj)
      // 将图片添加到图片上传组件的数组中
      if (newObj.image) {
        this.$refs.imageUpload.fileList = [{ url: newObj.image }]
      }
    }
  },
  created() {
    this.editLoadPage()
    this.getCategories()
    this.getAgents()
  },

  methods: {
    // 获取分类
    async getCategories() {
      const { data } = await getCategories()
      // console.log(145, res)
      data.forEach(item => {
        const cateObj = { value: item.id, label: item.title }
        this.categoryOption.push(cateObj)
      })
    },
    // 获取经纪
    async getAgents() {
      const { data } = await jingji()
      // console.log(154, data)
      data.forEach(item => {
        const agentObj = { value: item.id, label: item.name }
        this.agentOption.push(agentObj)
      })
      // console.log(160, this.agentOption)
    },
    // 编辑页面渲染
    async editLoadPage(id) {
      console.log(162, id)
      // 发请求
      await getPropertyById(id)
    },
    //   确认按钮
    async btnOk() {
      // 校验表单
      await this.$refs.formData.validate()
      const fileList = this.$refs.imageUpload.fileList
      this.formData.agent = this.agentValue
      this.formData.category = this.categoryValue

      console.log(190, this.formData)
      // console.log(53, this.formData)
      if (this.formData.id) {
        // console.log(68, this.formData)
        await delproperty({ ...this.formData, image: fileList[0] ? fileList[0].url : '' })
      } else {
        //   添加
        await addproperty({ ...this.formData, image: fileList[0] ? fileList[0].url : '' })
      }

      //   提示用户
      this.$message.success('操作成功')
      //   刷新页面
      //   this.$parent可以获取到父元素的实例,使用非常严格,该子组件不能嵌套在其他组件中
      this.$parent.loadPage()
      //   关闭模态框
      // this.$parent.isShowDialog = false
      // 关闭弹窗
      this.$emit('closeDialog')
    },
    // 取消按钮
    btnCancel() {
      // 清理数据
      this.formData = {
        agent: '',
        category: '',
        title: '',
        tags: [],
        address: '',
        price: '',
        desc: '',
        content: '',
        image: '',
        photos: []
      }
      this.$refs.imageUpload.fileList = []
      /*  this.formData.agent = ''
      this.formData.category = '' */
      //   清理校验
      this.$refs.formData.resetFields()
      // 关闭弹窗
      this.$emit('closeDialog')
    },
    //   富文本
    change(val) {
      this.formData.content = val
      console.log(this.formData)
    },
    //   图片
    // 删除图片
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.image = file.url
      this.dialogVisible = true
    },
    // 地址下拉框选中事件
    handleChange(value) {
      // console.log(value)
      // console.log(CodeToText[value[0]])
      const arr = []
      value.forEach(item => {
        arr.push(CodeToText[item])
      })
      console.log(arr)
      this.formData.address = arr.join(',')
      // console.log(this.address)
    },
    // 删除标签
    handleClose(tag) {
      this.formData.tags.splice(this.formData.tags.indexOf(tag), 1)
    },
    // 添加标签显示输入框
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 标签输入框失焦事件
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style>
</style>
